package com.beta.mq.redis.producer.worker;

import com.alibaba.fastjson.JSON;
import com.beta.mq.redis.model.Message;
import com.beta.mq.redis.producer.Producer;
import com.beta.mq.redis.producer.annotation.ToQueue;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.io.Serializable;

/**
 * 自动发送的切面
 *
 * @author taofucheng
 * @date 2015/12/8.
 */
@Aspect
@Slf4j
public class ProducerAspect {

    private Producer producer;

    public ProducerAspect(Producer producer) {
        this.producer = producer;
    }

    @Around("@annotation(toQueue)")
    public Object around(ProceedingJoinPoint point, ToQueue toQueue) {
        Object content = null;
        try {
            content = point.proceed();
            if (content != null && !(content instanceof Void)) {//不是无返回值的情况
                String topic = toQueue.topic();
                long expireAt =
                        toQueue.expire() == ToQueue.ExpireTime.NEVER_EXPIRES ?
                                ToQueue.ExpireTime.NEVER_EXPIRES :
                                System.currentTimeMillis() + toQueue.expire() * 1000;
                if (content instanceof Serializable) {
                    producer.sendMessage(topic, new Message(content, expireAt));
                } else {
                    producer.sendMessage(topic, new Message(JSON.toJSONString(content), expireAt));
                }
            }
        } catch (Throwable throwable) {
            //消息发送失败，不应该影响业务
            log.error("消息生产失败！{}", throwable.getMessage(), throwable);
        }
        return content;
    }

}
